package handler

import (
	"boy-go/modules/system/service"
	"boy-go/modules/system/vo"
	"boy-go/pkg/response"
	"boy-go/pkg/security"
	"github.com/gin-gonic/gin"
)

// AddSysLoginRouter 添加登陆路由
func AddSysLoginRouter(gin *gin.Engine) {
	gin.POST("/login", login)
	gin.POST("/logout", logout)
	gin.GET("/getInfo", security.VerifyToken, getInfo)
	gin.GET("/getRouters", security.VerifyToken, getRouters)
}

// login
// @Summary 系统用户登陆
// @Description 系统用户登陆（管理页面）
// @Tags auth
// @Accept json
// @Produce json
// @Param req body vo.LoginBody true "请求实体"
// @Success 200 {object} response.R[string] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /login [post]
func login(ctx *gin.Context) {
	var req = &vo.LoginBody{}
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxFailCode(ctx, response.ParamError)
		return
	}
	token, err := service.NewLoginService().Login(ctx, req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	ajax := response.NewAjaxResultSuccess()
	ajax.Put("token", token)
	response.AjaxResponse(ctx, ajax)
}
func logout(ctx *gin.Context) {
	response.AjaxSuccess(ctx, nil)
}

// getInfo
// @Summary 系统用户登陆
// @Description 系统用户登陆（管理页面）
// @Tags auth
// @Accept json
// @Produce json
// @Success 200 {object} response.R[vo.LoginUserInfo] "ok"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /getInfo [get]
func getInfo(ctx *gin.Context) {
	loginUser := security.GetLoginUser()
	if loginUser == nil {
		response.AjaxFailCode(ctx, response.Unauthorized)
		return
	}
	sysUser, err := service.NewSysUserService().SelectById(loginUser.UserId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	ajax := response.NewAjaxResultSuccess()
	ajax.Put("user", *sysUser)
	ajax.Put("roles", service.NewSysPermissionService().GetRolePermissionByUserId(sysUser.UserId))
	ajax.Put("permissions", service.NewSysPermissionService().GetMenuPermissionByUserId(sysUser.UserId))
	response.AjaxResponse(ctx, ajax)
}

func getRouters(ctx *gin.Context) {
	userId := security.GetLoginUserId()
	if userId == nil {
		response.AjaxFailCode(ctx, response.Unauthorized)
		return
	}
	menus, err := service.NewSysMenuService().SelectMenuTreeByUserId(*userId)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, service.NewSysMenuService().BuildMenus(menus))
}
